package com.one.group.admin.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.one.group.admin.dao.AdvertDao;
import com.one.group.admin.intercepter.AdminThreadLocal;
import com.one.group.enums.ErrorCode;
import com.one.group.model.dto.AdvertAddDto;
import com.one.group.model.dto.AdvertData;
import com.one.group.model.dto.AdvertQueryDto;
import com.one.group.model.dto.AdvertUpdateDto;
import com.one.group.model.entity.Admin;
import com.one.group.model.entity.Advert;
import com.one.group.model.entity.SpCell;
import com.one.group.model.entity.SpChargeStandards;
import com.one.group.model.vo.AdvertListVo;
import com.one.group.service.AdvertService;
import com.one.group.service.SpCellService;
import com.one.group.service.SpChargeStandardsService;
import com.one.group.utils.TencentCOS;
import com.one.group.utils.ThrowUtil;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author wanbo
 * @Date 2025/9/29 15:30
 */
@DubboService
@Slf4j
public class AdvertServiceImpl implements AdvertService {

    @Autowired
    private AdvertDao advertDao;

    @Autowired
    private SpChargeStandardsService spChargeStandardsService;

    @Autowired
    private SpCellService spCellService;

    @Override
    public AdvertListVo findAdvertListByCellId(String cellId) {
        AdvertListVo advertList = advertDao.findAdvertListByCellId(cellId);
        if (advertList.getCount()==0){
            ThrowUtil.throwIf(true, ErrorCode.NOT_FOUND_ERROR, "没有广告位");
        }
        return advertList;
    }

    @Override
    public Advert findAdvertById(String id) {
        if (id == null){
            log.error("查询广告参数错误");
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "id为空");
        }
        Advert advert = advertDao.findAdvertById(id);
        if (ObjectUtil.isEmpty(advert)){
            log.error("查询广告不存在：{}", id);
            return null;
        }
        if (advert.getStatus()!=0) {
            log.error("查询广告不存在：{}", id);
            return null;
        }
        return advert;
    }

    @Override
    public AdvertListVo findAdvertByQueryDto(AdvertQueryDto advertQueryDto) {
        if (ObjectUtil.isEmpty(advertQueryDto) ) {
            log.error("查询广告参数错误");
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR,"参数不能为空");
        }
        AdvertListVo advertListVo = advertDao.findAdvertByQueryDto(advertQueryDto);
        if (advertListVo.getCount()==0){
            log.error("查询广告不存在：{}", advertListVo);
            //ThrowUtil.throwIf(true, ErrorCode.NOT_FOUND_ERROR);
            return null;
        }
        return advertListVo;
    }

    @Override
    public void insertAdvertByUpload(AdvertData advertData) {
        if (ObjectUtil.isEmpty(advertData)){
            log.error("添加广告参数错误");
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        AdvertAddDto advertAddDto = new AdvertAddDto();
        advertAddDto.setChargeId(String.valueOf(6));
        QueryWrapper eqName = new QueryWrapper();
        // TODO 如果是管理员的话就设置tenantId   只能给管理员 1号管理不能用
        if (!StpUtil.getLoginId().equals("1")) {
            eqName.eq(SpCell::getTenantId, Convert.toLong(StpUtil.getExtra("tenant_id")));
        }
        advertAddDto.setCellId(String.valueOf(advertData.getCellId()));
        advertAddDto.setPosition(advertData.getPosition());
        advertAddDto.setSize(advertData.getSize());
        if (advertData.getPrice()!=null){
            advertAddDto.setPrice(advertData.getPrice());
        }
        this.inertAdvert(advertAddDto);
    }

    @Override
    public void inertAdvert(AdvertAddDto advertAddDto) {
        if (advertAddDto == null){
            log.error("添加广告参数错误");
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR);
        }

        if (advertAddDto.getCellId()==null || advertAddDto.getChargeId() == null || StrUtil.isEmpty(advertAddDto.getPosition()) || StrUtil.isEmpty(advertAddDto.getSize())){
            log.error("添加广告参数有空值：{}", advertAddDto);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "添加的参数不能为空");
        }

        Advert advert = new Advert();
        advert.setName("");
        advert.setStatus(0);
        advert.setCellId(String.valueOf(advertAddDto.getCellId()));
        advert.setChargeId(String.valueOf(advertAddDto.getChargeId()));
        advert.setPosition(advertAddDto.getPosition());
        advert.setSize(advertAddDto.getSize());
        if (advertAddDto.getPrice()!=null){
            advert.setPrice(advertAddDto.getPrice());
        } else {
            // 调用获取收费标准的服务
            SpChargeStandards spChargeStandard = spChargeStandardsService.getById(advertAddDto.getChargeId());
            advert.setPrice(spChargeStandard.getPrice());
        }
        advert.setImage("");
        // TODO 租户id要让小区的管理员记性设置   现在就只让总管理员进行
        if (StpUtil.getLoginId().equals("1")) {
            advert.setTenantId("1");
        }
        advert.setCreateTime(new Date());
        advert.setUpdateTime(new Date());
        advertDao.inertAdvert(advert);
    }

    private String generate16DigitId() {
        UUID uuid = UUID.randomUUID();

        long mostSignificantBits = uuid.getMostSignificantBits();
        long leastSignificantBits = uuid.getLeastSignificantBits();

        long[] longUUID = { mostSignificantBits, leastSignificantBits };
        return String.valueOf(longUUID);
    }

    @Override
    public void updateAdvert(AdvertUpdateDto advertUpdateDto) {
        if (advertUpdateDto == null){
            log.error("修改广告参数为空：{}", advertUpdateDto);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR,"广告修改的参数不能为空");
        }
        if (advertUpdateDto.getId()==null){
            log.error("修改广告参数错误：{}", advertUpdateDto);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "广告修改的参数不能为空");
        }
        if (advertUpdateDto.getCellId()==null){
            log.error("修改广告小区参数不能为空：{}", advertUpdateDto.getCellId());
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "修改的参数不能为空");
        }
        if (advertUpdateDto.getChargeId()==null){
            log.error("修改广告收费标准参数不能为空：{}", advertUpdateDto.getChargeId());
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "修改的参数不能为空");
        }
        Advert advert = new Advert();

        advert.setId(String.valueOf(advertUpdateDto.getId()));
        advert.setName(StrUtil.isEmpty(advertUpdateDto.getName()) ? "" : advertUpdateDto.getName());
        if (0 == advertUpdateDto.getStatus()) {
            advert.setStatus(0);
        } else {
            advert.setStatus(1);
        }
        advert.setCellId(String.valueOf(advertUpdateDto.getCellId()));
        advert.setChargeId(String.valueOf(advertUpdateDto.getChargeId()));
        advert.setPosition(advertUpdateDto.getPosition());
        advert.setSize(advertUpdateDto.getSize());
        advert.setPrice(advertUpdateDto.getPrice());
        advert.setImage(StrUtil.isEmpty(advertUpdateDto.getImage()) ? "" : advertUpdateDto.getImage());
        advert.setTenantId(String.valueOf(advertUpdateDto.getTenantId()));
        advert.setCreateTime(advertUpdateDto.getCreateTime());
        advert.setUpdateTime(new Date());

        advertDao.updateAdvert(advert);
    }

    @Override
    @Operation(summary = "删除广告")
    public void deleteAdvertById(String id) {
        if (id == null){
            log.error("删除广告的参数为空：{}", id);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "删除广告的id不能为空");
        }
        advertDao.deleteAdvertById(id);
    }

    @Override
    public void insertAdvertList(List<Advert> advertList) {
        advertDao.insertAdvertList(advertList);
    }

    @Override
    public void deleteBatch(List<String> ids) {
        if (ids == null || ids.size() == 0){
            log.error("批量删除广告的参数为空：{}", ids);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "批量删除广告的参数不能为空");
        }
        advertDao.deleteBatch(ids);
    }

}
